import axios from "axios";
import {Message} from "element-ui";
import router from "@/router";
import store from "@/store"

//请求拦截器
// axios.interceptors.request.use(config=>{
//     if (sessionStorage.getItem("token_login")){
//         config.headers["Authorization"]=sessionStorage.getItem("token_login")
//     }
//     return config;
// },error => {
//     console.log(error)
// })

// 响应拦截器
axios.interceptors.response.use(
    (success) => {
        if (success.status && success.status == 200) {
            let code = success.data.code;
            if (code == 5000 || code == 4001 || code == 4003 || code == 5002) {
                Message.error({message: success.data.message})
                return;
            }
            return success.data;
        }
    }, error => {
        let sta = error.response.status;
        if (sta == 504 || sta == 404) {
            Message.error({message: "服务器被吃了"})
        } else if (sta == 403) {
            Message.error({message: "权限不足，请联系管理员"})
        } else if (sta == 401) {
            Message.error({message: "未登录，请登录！"})
            store.commit("logout")
            router.replace({path:"/login"})
        } else if (error.response.data.message) {
            Message.error({message: error.response.data.message})
        } else {
            Message.error({message: "未知错误，请联系管理员"})
        }
        return;
    })

let prefix = '';
export const postRequest = (url, params) => {
    return axios({
        method: "post",
        url: `${prefix}${url}`,
        data: params
    })
}

export const getRequest = (url, params) => {
    return axios({
        method: "get",
        url: `${prefix}${url}`,
        data: params
    })
}

export const putRequest = (url, params) => {
    return axios({
        method: "put",
        url: `${prefix}${url}`,
        data: params
    })
}

export const deleteRequest = (url, params) => {
    return axios({
        method: "delete",
        url: `${prefix}${url}`,
        data: params
    })
}